//
//  SearchViewController.m
//  HappinessTrip
//
//  Created by dllo on 15/10/19.
//  Copyright © 2015年 蓝鸥科技. All rights reserved.
//

#import "SearchViewController.h"
#import "GetDataMethods.h"
#import "SearchPlace.h"
#import "SearchTrips.h"
#import "Model.h"
#import "Fit.h"
#import "OtherViewController.h"
#import "DownDetailsViewController.h"
#import "MJRefresh.h"
#import "MBProgressHUD.h"
#import "SearchPlaceTableViewCell.h"
#import "SearchTripsTableViewCell.h"

@interface SearchViewController ()<UITableViewDataSource, UITableViewDelegate>
@property(nonatomic, retain)UITableView *tableView;
@property(nonatomic, retain)NSMutableArray *tripsArray;
@property(nonatomic, retain)NSMutableArray *placeArray;
@property(nonatomic, assign)NSInteger number;
@property(nonatomic, retain)MBProgressHUD *progressView;

@end

@implementation SearchViewController
-(void)dealloc
{
    [_tableView release];
    [_tripsArray release];
    [_placeArray release];
    
    [super dealloc];
}

-(void)changeColor{
    self.tableView.backgroundColor = [Model shareInstance].BackgroundColor;
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[Model shareInstance].TitleColor, NSForegroundColorAttributeName, nil]];
    self.navigationController.navigationBar.barTintColor = [Model shareInstance].BackgroundColor;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.tripsArray = [NSMutableArray array];
    self.placeArray = [NSMutableArray array];
    [self reloadDataAndRefresh];
    [self changeColor];
    [self getData];
    
}

-(void)loadView
{
    [super loadView];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeColor) name:@"changeColor" object:nil];
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 113) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = [UIColor colorWithRed:1 green:0.95 blue:0.85 alpha:1];
    [self.view addSubview:_tableView];
    [_tableView release];
    
    //加载视图初始化
    self.progressView = [[MBProgressHUD alloc]initWithView:self.view];
    _progressView.labelText = @"玩命加载中";
    [_progressView setMode:MBProgressHUDModeIndeterminate];
    [_progressView show:YES];
    _progressView.backgroundColor = [UIColor colorWithRed:0.73 green:0.76 blue:0.77 alpha:.3];
    [self.view addSubview:_progressView];
    [_progressView release];
    
}

-(void)getData
{
    
    if (_urlString.length == 0) {
        return;
    }
    NSString *string = [NSString stringWithFormat:@"http://api.breadtrip.com/search/?key=%@&start=%ld&count=20", _urlString, _number];
    [GetDataMethods getDataByString:string BodyString:nil WithDataBlock:^(id data) {
        NSArray *tArray = [data objectForKey:@"trips"];
        for (NSDictionary *tDic in tArray) {
            SearchTrips *trip = [[SearchTrips alloc]init];
            [trip setValuesForKeysWithDictionary:tDic];
            [_tripsArray addObject:trip];
        }
        NSArray *pArray = [data objectForKey:@"places"];
        for (NSDictionary *pDic in pArray) {
            SearchPlace *place = [[SearchPlace alloc]init];
            [place setValuesForKeysWithDictionary:pDic];
            [_placeArray addObject:place];
        }
        [_tableView reloadData];
        [_tableView.header endRefreshing];
        [_tableView.footer endRefreshing];
        [_progressView removeFromSuperview];
        
    }];
}

-(void)reloadDataAndRefresh
{
    _tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [_tripsArray removeAllObjects];
        [_placeArray removeAllObjects];
        _number = 0;
        [self getData];
        
    }];
    _tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _number += 20;
        [self getData];
    }];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        static NSString *identifier = @"cell";
        SearchPlaceTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (!cell) {
            cell = [[SearchPlaceTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        }
        if (_placeArray.count != 0) {
            NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc]initWithString:[_placeArray[indexPath.row] name]];
            NSRange range = [[_placeArray[indexPath.row] name] rangeOfString:_urlString];
            [attributeString setAttributes:[NSMutableDictionary dictionaryWithObjectsAndKeys:[UIColor redColor], NSForegroundColorAttributeName, [UIFont systemFontOfSize:18], NSFontAttributeName, nil] range:range];
            cell.search = _placeArray[indexPath.row];
            cell.label.attributedText = attributeString;
        }
        cell.backgroundColor = [Model shareInstance].BackgroundColor;
        return cell;
    }
    static NSString *identifier1 = @"cell1";
    SearchTripsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier1];
    if (!cell) {
        cell = [[SearchTripsTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier1];
    }
    if (_tripsArray.count != 0) {
        NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc]initWithString:[_tripsArray[indexPath.row] name]];
        NSRange range = [[_tripsArray[indexPath.row] name] rangeOfString:_urlString];
        [attributeString setAttributes:[NSMutableDictionary dictionaryWithObjectsAndKeys:[UIColor redColor], NSForegroundColorAttributeName, [UIFont systemFontOfSize:18], NSFontAttributeName, nil] range:range];
        cell.search = _tripsArray[indexPath.row];
        cell.nameLabel.attributedText = attributeString;
    }
    cell.backgroundColor = [Model shareInstance].BackgroundColor;
    return cell;

}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return _placeArray.count;
    }
    return _tripsArray.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 40 * H;
    }
    else {
        return 100 * H;
    }
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 40 * H;
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSArray *array = @[@"城市", @"游记"];
    return array[section];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        OtherViewController *otherVC = [[OtherViewController alloc]init];
        if (_placeArray.count != 0) {
            otherVC.data = _placeArray[indexPath.row];
        }
        [self.navigationController pushViewController:otherVC animated:YES];
    }
    else {
        DownDetailsViewController *downVC = [[DownDetailsViewController alloc]init];
        if (_tripsArray.count != 0) {
            downVC.string = [_tripsArray[indexPath.row] Id];
        }
        [self.navigationController pushViewController:downVC animated:YES];
    }
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
